<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 500px"
    :inline="true"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item>
      <el-date-picker
        v-model="ruleForm.startDate"
        :disabled="true"
        type="date"
        placeholder="Pick a day"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
        @change="datechange"
      />
    </el-form-item>
    <el-form-item label="入住天数" prop="days">
      <el-input-number
        v-model.number="ruleForm.days"
        clearable
        style="width: 100px"
        :min="1"
        @change="getTotalPrice"
      />
    </el-form-item>
    <el-form-item label="基本信息" style="display: block">
      <el-card>
        <el-form-item label="房间号" prop="roomNumber">
          <el-input v-model="ruleForm.roomNumber" :disabled="true" />
        </el-form-item>
        <el-form-item label="总价格">
          <el-input v-model="TotalPrice" :disabled="true" />
        </el-form-item>
        <el-form-item label="押金">
          <el-input v-model="deposit" :disabled="true" />
        </el-form-item>
      </el-card>
    </el-form-item>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="联系人">
          <el-input v-model="ruleForm.contact" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="电话号码">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
      </el-col>
    </el-row>
    <div v-for="(item, index) in infoList" :key="index">
      <el-row :gutter="20">
        <!-- 姓名列 -->
        <el-col :span="7">
          <el-form-item label="姓名">
            <el-input v-model="item.customerName" style="width: 90px" />
          </el-form-item>
        </el-col>
        <!-- 身份证列 -->
        <el-col :span="13">
          <el-form-item label="身份证">
            <el-input v-model="item.idCard" style="width: 200px" />
          </el-form-item>
        </el-col>
        <!-- 操作按钮列 -->
        <el-col :span="4">
          <!-- 第一行显示加减号 -->
          <template v-if="index === 0">
            <el-button
              type="primary"
              :icon="Plus"
              circle
              size="small"
              @click="addRow(index)"
            />
            <el-button
              type="danger"
              :icon="Minus"
              circle
              size="small"
              :disabled="infoList.length === 1"
              @click="removeRow(index)"
            />
          </template>
          <!-- 其他行只显示减号 -->
          <template v-else>
            <el-button
              type="danger"
              :icon="Minus"
              circle
              size="small"
              :disabled="infoList.length === 1"
              @click="removeRow(index)"
            />
          </template>
        </el-col>
      </el-row>
    </div>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
      <el-button type="info" @click="reset()">重置</el-button>
      <el-button @click="close">关 闭</el-button>
    </el-form-item>
  </el-form>
  <el-drawer
    v-model="drawer"
    title="选择支付方式"
    direction="btt"
    :before-close="handleClose"
    size="45%"
  >
    <div class="payment-options">
      <div
        v-for="option in paymentOptions"
        :key="option.value"
        class="option"
        :class="{ selected: selectedPayment === option.value }"
        @click="selectPayment(option.value)"
      >
        {{ option.label }}
      </div>
    </div>
    <div class="button-group">
      <el-button type="primary" @click="confirmPayment">确定</el-button>
    </div>
  </el-drawer>
  <!-- 微信支付弹窗 -->
  <el-dialog v-model="wechatDialogVisible" width="300">
    <el-form>
      <el-form-item
        label="应付金额"
        :rules="[
          { required: true, message: '应付金额不能为空', trigger: 'blur' }
        ]"
      >
        <el-input :value="amountToPay" :disabled="true" />
      </el-form-item>
      <el-button @click="calculateChange">支付</el-button>
    </el-form>
  </el-dialog>
  <!-- 现金支付弹窗 -->
  <el-dialog v-model="cashDialogVisible" width="300" @close="handleDialogClose">
    <el-form :model="paymentForm">
      <el-form-item label="实付金额">
        <el-input v-model="paymentForm.paidAmount" />
      </el-form-item>
      <el-form-item
        label="应付金额"
        prop="amountToPay"
        :rules="[
          { required: true, message: '应付金额不能为空', trigger: 'blur' }
        ]"
      >
        <el-input :value="amountToPay" :disabled="true" />
      </el-form-item>
      <el-form-item label="找零金额">
        <el-input :value="change" :disabled="true" />
      </el-form-item>
      <el-button @click="calculateChange">找零</el-button>
    </el-form>
  </el-dialog>
  <!-- 支付宝支付弹窗 -->
  <el-dialog v-model="alipayDialogVisible" width="500">
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: center;
        height: 300px;
      "
    >
      <img :src="imgUrl" alt="" style="width: 300px" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="refresh">刷新二维码</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type ComponentSize,
  type FormInstance,
  type FormRules
} from "element-plus";
import { type RoomtypesForm } from "@/api/roomtypes";

import {
  RoomCheckInForm,
  getPriceTotal,
  addCheckInfo,
  getDepositByRoomNumber,
  cashPay,
  wechatPay
} from "@/api/roomsale";
import { Plus, Minus, Coin } from "@element-plus/icons-vue";

/** ------------------组件通信-接收数据-------------------- */
const emit = defineEmits(["close"]);
const props = defineProps({
  dialogOpen: {
    type: Boolean,
    default: null
  },
  roomNumber: {
    type: String,
    default: null
  }
});
const ruleForm = ref<RoomCheckInForm>({
  roomNumber: undefined,
  contact: undefined,
  phone: undefined,
  startDate: undefined,
  days: undefined,
  information: undefined
});
watch(
  () => props.dialogOpen,
  (newDialogOpen, oldDialogOpen) => {
    if (newDialogOpen === false) {
      close();
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.roomNumber,
  (newroomNumber, oldroomNumber) => {
    ruleForm.value.roomNumber = newroomNumber;
    if (newroomNumber !== null) {
      initData();
    }
  },
  { deep: true, immediate: true }
);

/** ------------------加载初始化数据-------------------- */
const deposit = ref<number>();
const today = new Date();
function initData() {
  setTimeout(() => {
    ruleForm.value.startDate =
      today.getFullYear() +
      "-" +
      String(today.getMonth() + 1).padStart(2, "0") +
      "-" +
      String(today.getDate()).padStart(2, "0");
    ruleForm.value.days = 1;
    getPriceTotal(ruleForm.value).then(response => {
      TotalPrice.value = response.data;
    });
    getDepositByRoomNumber(ruleForm.value.roomNumber).then(response => {
      deposit.value = response.data;
      console.log("deposit", deposit.value);
    });
  }, 50);
}

/** ------------------表单数据-------------------- */
// 表单属性size
const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();

//表单校验规则
const rules = reactive<FormRules<RoomtypesForm>>({
  // roomTypesName: [{ required: true, message: "类别名称不能为空", trigger: "change" }]
  // type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  // name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  // beds: [
  //   { required: true, message: "类型不能为空", trigger: "blur" },
  //   {
  //     pattern: /^[1-9]$/,
  //     message: "范围1-9",
  //     trigger: "blur"
  //   }
  // ],
  // basicPrice: [
  //   {
  //     pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
  //     required: true,
  //     message: "价格格式不正确, 参考20.50",
  //     trigger: "blur"
  //   }
  // ],
  // level: [{ required: true, message: "等级不能为空", trigger: "blur" }]
});

let debounceTimer = null;
function getTotalPrice() {
  clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    getPriceTotal(ruleForm.value).then(response => {
      TotalPrice.value = response.data;
    });
  }, 300);
}
function datechange() {
  ruleForm.value.days = 1;
  getPriceTotal(ruleForm.value).then(response => {
    TotalPrice.value = response.data;
  });
}

const TotalPrice = ref<number>();
const imgUrl = ref("");

const wechatDialogVisible = ref(false);
const alipayDialogVisible = ref(false);
const cashDialogVisible = ref(false);
const paymentDialogVisible = ref(false);
/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
  ruleForm.value.information = infoList.value
    .map(item => `${item.customerName}:${item.idCard}`)
    .join(",");
  // paymentDialogVisible.value = true;
  drawer.value = true;

  // qrcodeLoading.value = true;
  // close();
};

const getQrCodeImg = () => {
  try {
    imgUrl.value = `http://common.free.idcfengye.com/hotel/sale/alipay/getQrCode?t=${Date.now()}`;
  } catch (error) {
    ElMessage.error("获取二维码失败");
  }
};
// 定义响应式数组
const infoList = ref<Array<{ customerName: string; idCard: string }>>([
  {
    customerName: "",
    idCard: ""
  }
]);

// 添加行
const addRow = (index: number) => {
  infoList.value.push({ customerName: "", idCard: "" });
};

// 删除行
const removeRow = (index: number) => {
  if (infoList.value.length > 1) {
    infoList.value.splice(index, 1);
  }
};

/** 重置表单 */
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

function reset() {
  resetForm(ruleFormRef.value);
  initData();
  TotalPrice.value = undefined;
  ruleForm.value.contact = undefined;
  ruleForm.value.phone = undefined;
  infoList.value = [
    {
      customerName: "",
      idCard: ""
    }
  ];
}
function refresh() {
  getQrCodeImg();
}

function close() {
  reset();
  emit("close");
}

const drawer = ref(false);

const paymentOptions = [
  { value: "alipay", label: "支付宝支付" },
  { value: "wechat", label: "微信支付" },
  { value: "cash", label: "现金支付" }
];
const selectedPayment = ref("");

const handleClose = done => {
  ElMessageBox.confirm("是否取消支付？")
    .then(() => {
      drawer.value = false;
      done();
    })
    .catch(() => {
      // 取消关闭操作
    });
};

const selectPayment = value => {
  selectedPayment.value = value;
  console.log(selectedPayment.value);
};

const confirmPayment = () => {
  // 确认支付逻辑
  console.log(`支付方式选择为: ${selectedPayment.value}`);
  drawer.value = false; // 关闭抽屉，不显示确认弹窗
  closePaymentDialog();
};

//--------------------------------------------------
const closePaymentDialog = () => {
  paymentDialogVisible.value = false;

  switch (selectedPayment.value) {
    case "wechat":
      wechatDialogVisible.value = true;
      console.log("微信支付");
      break;
    case "alipay":
      alipayDialogVisible.value = true;
      addCheckInfo(ruleForm.value).then(response => {
        getQrCodeImg();
      });
      console.log(imgUrl.value);
      break;
    case "cash":
      cashDialogVisible.value = true;
      break;
    default:
      console.log("未选择支付方式");
  }
};

const paymentForm = ref({
  paidAmount: 0
});

// 计算应付金额
const amountToPay = computed(() => {
  return TotalPrice.value + deposit.value;
});

// 计算找零金额
const change = ref<number>();

// 获取总价格的逻辑
const getTotalPayPrice = () => {
  // 这里根据你的业务逻辑来设置 TotalPrice 和 deposit 的值
  TotalPrice.value = 500; // 示例值
  deposit.value = 100; // 示例值
};

// 计算找零金额的逻辑
// 对话框关闭或失焦时清空数据
const handleDialogClose = () => {
  cashDialogVisible.value = false;
  paymentForm.value.paidAmount = 0;
  change.value = 0;
};

// 计算找零方法
const calculateChange = () => {
  if (cashDialogVisible.value === true) {
    alert("现金支付");
    if (!paymentForm.value.paidAmount) {
      ElMessage.warning("请输入实付金额");
      return;
    }
    if (paymentForm.value.paidAmount < amountToPay.value) {
      ElMessage.warning("实付金额不足");
      return;
    }
    change.value = paymentForm.value.paidAmount - amountToPay.value;
    cashPay(ruleForm.value).then(response => {
      if (response.code === 200) {
        ElMessage({
          type: "success",
          message: response.msg
        });
        cashDialogVisible.value = false;
      } else {
        ElMessage({
          type: "error",
          message: response.msg
        });
      }
    });
  } else {
    wechatPay(ruleForm.value).then(response => {
      alert("微信支付");
      if (response.code === 200) {
        ElMessage({
          type: "success",
          message: response.msg
        });
        cashDialogVisible.value = false;
      } else {
        ElMessage({
          type: "error",
          message: response.msg
        });
      }
    });
  }
};
</script>

<style scoped>
.payment-options {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 16px;
}

.option {
  width: 100%;
  padding: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
}

.selected {
  background-color: #b2eff7;
  border-color: #6ee868;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
